// components/goods-detail-property-select-c/goods-detail-property-select-c.js商品选择框
let common_js = require("../../utils/common.js");

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsItem: {
      type: Object,
      value: null,
      observer(newVal, oldVal, changedPath) {
        if (newVal) {
          //设置数据
          this.initData(newVal);
        }
      }
    },
    dismiss: {
      type: Boolean,
      value: false,
      observer(newVal, oldVal, changedPath) {
        if (newVal) {
          //动画
          this.goodsPropertyViewShowWithAnimation(false);
          //回调
          setTimeout(() => {
            this.onHide();
          }, 400);
        }
      }
    },
  },

  ready: function () {
    //展示试图
    this.goodsPropertyViewShowWithAnimation(true);
  },

  /**
   * 组件的初始数据
   */
  data: {
    //动画
    goodsPropertyMoveAnimation: {
      data: null,
      animation: null,
      bottom: -405
    },
    dimensionsList: [],
    dimensionsSelectedIndexList: [], //存放选中状态
    skuList: [],
    count: 1,
    selectDimensionValue: {},
    selectedSkuItem: null,
    promotionPrice: '', //促销价格
    price: '', //原价
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //阻止事件传递
    onTap: function (e) {},
    //判断是否是活动商品----不包括拼团
    isActivityGoods(type) {
      let flag = false;
      if (type == 2 || type == 3 || type == 4) {
        flag = true;
      }
      return flag;
    },
    //初始化数据
    initData: function (res) {
      //0.1拼团活动单规格单独处理
      if (res.type == 1 && res.skuList.length == 1) {
        this.initPtNoSpecificationData(res);
        return;
      }
      //0.2立即购买单规格单独处理--除拼团商品，其他商品的立即购买
      if (res.type != 1 && res.skuList.length == 1) {
        this.initNormalGoodsNoSpecificationData(res);
        return;
      }

      //正常商品、限时抢购商品，拼团
      //展示的属性的集合
      let tmpDimensionsList = [];
      let tmpDimensionsSelectedIndexList = [];

      let tmpSet = new Set();
      for (let i = 0; i < res.skuList.length; i++) {
        let item = res.skuList[i];
        let dimensionValuesSet = null;
        //1.1正常商品
        //1.2拼团单独购
        if (res.type == 0 || (res.type == 1 && res.ptType == '1')) {
          if (item.dimensionValue && item.stock > 0) {
            dimensionValuesSet = new Set(Object.values(item.dimensionValue));
          } else {
            dimensionValuesSet = new Set();
          }
        } else if ((res.type == 1 && res.isFqpt) || this.isActivityGoods(res.type)) {
          //2.1多规格的发起拼团
          //2.2活动商品
          if (item.dimensionValue && item.stockLeft > 0) {
            dimensionValuesSet = new Set(Object.values(item.dimensionValue));
          } else {
            dimensionValuesSet = new Set();
          }
        }

        //并集
        let valuesArray = Array.from(dimensionValuesSet);
        for (let j = 0; j < valuesArray.length; j++) {
          let value = valuesArray[j];
          tmpSet.add(value);
        }
      }

      //初始化数据
      for (let i = 0; i < res.dimensions.length; i++) {
        let item = res.dimensions[i];
        let valuesList = item.values;

        let tmpDimensionsValuesList = [];
        for (let j = 0; j < valuesList.length; j++) {
          let obj = {};
          let valueItem = valuesList[j];
          let valueSet = new Set([valueItem]);
          //交集
          let intersect = [...new Set([...tmpSet].filter(n => valueSet.has(n)))];
          if (Array.from(intersect).length > 0) {
            obj.canNotBuy = false;
          } else {
            obj.canNotBuy = true;
          }
          obj.value = valueItem;
          tmpDimensionsValuesList.push(obj);
        }

        let tmpDimensionItem = {};
        tmpDimensionItem.name = item.name;
        tmpDimensionItem.values = tmpDimensionsValuesList;
        tmpDimensionsList.push(tmpDimensionItem);
        //index
        let tmpSelectedInfo = {
          sIndex: -1,
          index: -1
        };
        tmpDimensionsSelectedIndexList.push(tmpSelectedInfo);
      }

      let tmpPromotionPrice = '';
      let tmpPrice = '';

      if (res.type == 0 || (res.type == 1 && res.ptType == '1')) {
        //1.正常商品
        tmpPromotionPrice = res.minPrice;
        tmpPrice = res.minCrossedPrice;
      } else if ((res.type == 1 && res.isFqpt) || this.isActivityGoods(res.type)) {
        //2.1多规格的发起拼团
        //2.2活动商品
        tmpPromotionPrice = res.minPromotionPrice;
        tmpPrice = res.minPrice;
      }

      //设置数据
      this.setData({
        dimensionsSelectedIndexList: tmpDimensionsSelectedIndexList,
        dimensionsList: tmpDimensionsList,
        skuList: res.skuList,
        promotionPrice: tmpPromotionPrice,
        price: tmpPrice
      });
    },

    //初始化拼团活动状态---没有规格，只展示数量-----单独处理
    initPtNoSpecificationData: function (res) {
      // 单一规格单独处理，其他不显示这个规格
      let skuItem = res.skuList[0];
      let tmpPromotionPrice = '';
      let tmpPrice = '';
      //单独购买，只显示原价
      if (res.ptType == '1') {
        tmpPromotionPrice = skuItem.price;
        tmpPrice = skuItem.crossedPrice;
      }
      if (res.isFqpt) {
        tmpPromotionPrice = skuItem.promotionPrice;
        tmpPrice = skuItem.price;
      }
      this.setData({
        promotionPrice: tmpPromotionPrice,
        price: tmpPrice,
        selectedSkuItem: skuItem
      });
    },

    //初始化正常商品立即购买---没有规格，只展示数量-----单独处理
    initNormalGoodsNoSpecificationData(res) {
      // 单一规格单独处理，其他不显示这个规格
      let skuItem = res.skuList[0];
      let tmpPromotionPrice = '';
      let tmpPrice = '';

      if (res.isBuyRightNow) {
        //正常商品
        if (res.type == 0) {
          //只有原价
          tmpPromotionPrice = res.minPrice;
          tmpPrice = res.minCrossedPrice;
        } else {
          //促销或者团购的话有原价和促销价
          tmpPromotionPrice = res.minPromotionPrice;
          tmpPrice = res.minPrice;
        }
      }
      this.setData({
        promotionPrice: tmpPromotionPrice,
        price: tmpPrice,
        selectedSkuItem: skuItem
      });
    },

    //属性选择动画
    goodsPropertyViewShowWithAnimation: function (show) {
      if (!this.data.goodsPropertyMoveAnimation.animation) {
        let tempMoveAnimation = this.data.goodsPropertyMoveAnimation;
        let animation = wx.createAnimation({
          timingFunction: 'ease',
        });
        tempMoveAnimation.animation = animation;
        this.setData({
          moveAnimation: tempMoveAnimation
        });
      }
      let tempMoveAnimation = this.data.goodsPropertyMoveAnimation;
      if (show) {
        tempMoveAnimation.bottom = -405;
      } else {
        tempMoveAnimation.bottom = 405;
      }
      tempMoveAnimation.animation.translateY(tempMoveAnimation.bottom).step();
      tempMoveAnimation.data = tempMoveAnimation.animation.export();
      this.setData({
        goodsPropertyMoveAnimation: tempMoveAnimation
      });
    },

    //选择商品的属性
    onPropertyValueItem: function (e) {
      //superIndex
      let sIndex = e.currentTarget.dataset.sindex;
      //index
      let index = e.currentTarget.dataset.index;
      //选中的属性列表
      let tmpDimensionsList = this.data.dimensionsList;
      let sItem = tmpDimensionsList[sIndex];
      let sValuesItem = sItem.values[index];
      if (sValuesItem.canNotBuy) return;

      //判断选中状态
      let tmpDimensionsSelectedIndexList = this.data.dimensionsSelectedIndexList;
      let tmpSelectedIndexInfo = tmpDimensionsSelectedIndexList[sIndex];
      if (tmpSelectedIndexInfo.sIndex != -1) {
        //选中的是同一个 return
        if (tmpSelectedIndexInfo.sIndex == sIndex && tmpSelectedIndexInfo.index == index) {
          return
        } else {
          //reset last, set next
          let lastItem = sItem.values[tmpSelectedIndexInfo.index];
          lastItem.selected = false;
          //set current
          sValuesItem.selected = true;
        }
      } else {
        sValuesItem.selected = true;
      }

      tmpSelectedIndexInfo.sIndex = sIndex;
      tmpSelectedIndexInfo.index = index;

      //更新其他属性是否可以点击
      this.updateOtherDimensionValues(tmpSelectedIndexInfo);
      //设置选择的属性dimensionValue
      let tmpSelectedDimensionValue = this.data.selectDimensionValue;
      let key = sItem.name;
      tmpSelectedDimensionValue[key] = sValuesItem.value;
      if (Object.keys(tmpSelectedDimensionValue).length == tmpDimensionsList.length) {
        this.getSelectedSkuItem(this.data.selectDimensionValue);
      }

      // set data
      this.setData({
        selectDimensionValue: tmpSelectedDimensionValue,
        dimensionsSelectedIndexList: tmpDimensionsSelectedIndexList,
        dimensionsList: tmpDimensionsList
      });
    },

    //更新商品其他属性是否可以点击
    updateOtherDimensionValues: function (selectedIndexInfo) {
      let sIndex = selectedIndexInfo.sIndex;
      //index
      let index = selectedIndexInfo.index;

      let tmpDimensionsList = this.data.dimensionsList;
      let sItem = tmpDimensionsList[sIndex];
      let sValuesItem = sItem.values[index];

      //当前所有其他属性值的集合
      let tmpSet = new Set();
      for (let i = 0; i < this.data.skuList.length; i++) {
        let item = this.data.skuList[i];
        //1.1正常商品
        //1.2拼团单独购
        if (this.data.goodsItem.type == 0 || (this.data.goodsItem.type == 1 && this.data.goodsItem.ptType == '1')) {
          if ((item.dimensionValue[sItem.name] == sValuesItem.value) && item.stock > 0) {
            let dimensionValuesSet = new Set(Object.values(item.dimensionValue));
            let valueSet = new Set([sValuesItem.value]);
            //差集
            let difference = [...new Set([...dimensionValuesSet].filter(n => !valueSet.has(n)))];
            let differenceArray = Array.from(difference);
            for (let j = 0; j < differenceArray.length; j++) {
              let value = differenceArray[j];
              tmpSet.add(value);
            }
          }
        } else if ((this.data.goodsItem.type == 1 && this.data.goodsItem.isFqpt) || this.isActivityGoods(this.data.goodsItem.type)) {
          //2.1多规格的发起拼团
          //2.活动商品
          if ((item.dimensionValue[sItem.name] == sValuesItem.value) && item.stockLeft > 0) {
            let dimensionValuesSet = new Set(Object.values(item.dimensionValue));
            let valueSet = new Set([sValuesItem.value]);
            //差集
            let difference = [...new Set([...dimensionValuesSet].filter(n => !valueSet.has(n)))];
            let differenceArray = Array.from(difference);
            for (let j = 0; j < differenceArray.length; j++) {
              let value = differenceArray[j];
              tmpSet.add(value);
            }
          }
        }
      }

      //初始化数据
      for (let i = 0; i < tmpDimensionsList.length; i++) {
        let item = tmpDimensionsList[i];
        if (i != sIndex) {
          let valuesList = item.values;
          for (let j = 0; j < valuesList.length; j++) {
            let valueItem = valuesList[j];
            let valueSet = new Set([valueItem.value]);
            //交集
            let intersect = [...new Set([...tmpSet].filter(n => valueSet.has(n)))];
            if (Array.from(intersect).length > 0) {
              valueItem.canNotBuy = false;
            } else {
              valueItem.canNotBuy = true;
            }
          }
        }
      }
      //set data
      this.setData({
        dimensionsList: tmpDimensionsList
      });
    },

    //根据选中的属性找到skuList对应的item
    getSelectedSkuItem: function (selectDimensionValue) {
      for (let i = 0; i < this.data.skuList.length; i++) {
        let item = this.data.skuList[i];
        let tmpDimensionValue = item.dimensionValue;
        //比较两个对象值是否一致
        if (common_js.isObjectValueEqual(tmpDimensionValue, selectDimensionValue)) {
          //更新两个价格
          let tmpPromotionPrice = '';
          let tmpPrice = '';
          //1.1正常商品
          //1.2商品单独购买
          if (this.data.goodsItem.type == 0 || (this.data.goodsItem.type == 1 && this.data.goodsItem.ptType == '1')) {
            tmpPromotionPrice = item.price;
            tmpPrice = item.crossedPrice;
          } else if ((this.data.goodsItem.type == 1 && this.data.goodsItem.isFqpt) || this.isActivityGoods(this.data.goodsItem.type)) {
            //2.1多规格的发起拼团
            //2.活动商品
            tmpPromotionPrice = item.promotionPrice;
            tmpPrice = item.price;
          }

          //set data
          this.setData({
            promotionPrice: tmpPromotionPrice,
            price: tmpPrice,
            selectedSkuItem: item
          });
          return;
        }
      }
    },

    //减商品
    onMinus: function (e) {
      if (!this.data.selectedSkuItem) {
        common_js.showToast("请选择商品规格");
        return;
      }

      let tempCount = this.data.count;
      tempCount--;
      if (tempCount == 0) {
        tempCount = 1;
      }
      this.setData({
        count: tempCount
      });
    },

    //加商品
    onAdd: function (e) {
      if (!this.data.selectedSkuItem) {
        common_js.showToast("请选择商品规格");
        return;
      }
      //
      let tempCount = this.data.count;
      tempCount++;
      // 正常商品
      if (this.data.goodsItem.type == 0 || (this.data.goodsItem.type == 1 && this.data.goodsItem.ptType == '1')) {
        // stock
        if (tempCount > this.data.selectedSkuItem.stock) {
          common_js.showToast("库存不足");
          tempCount--;
          return;
        }
      } else if ((this.data.goodsItem.type == 1 && this.data.goodsItem.isFqpt) || this.isActivityGoods(this.data.goodsItem.type)) {
        //2.1多规格的发起拼团
        if (tempCount > this.data.selectedSkuItem.stockLeft) {
          common_js.showToast("库存不足");
          tempCount--;
          return;
        }
      }
      this.setData({
        count: tempCount
      });
    },

    //view消失
    onHide: function () {
      this.triggerEvent('hidden', null, {});
    },

    onEnsure: function () {
      //1.
      if (!this.data.selectedSkuItem) {
        common_js.showToast("请选择商品规格");
        return;
      }
      //2.拼团无规格类型选择
      if (this.data.goodsItem.type == 0 || (this.data.goodsItem.type == 1 && this.data.goodsItem.ptType == '1')) {
        // stock
        if (this.data.count > this.data.selectedSkuItem.stock) {
          common_js.showToast("库存不足");
          return;
        }
      } else if ((this.data.goodsItem.type == 1 && this.data.goodsItem.isFqpt) || this.isActivityGoods(this.data.goodsItem.type)) {
        //2.1多规格的发起拼团
        if (this.data.count > this.data.selectedSkuItem.stockLeft) {
          common_js.showToast("库存不足");
          return;
        }
      }
      //3动画结束，回调
      this.goodsPropertyViewShowWithAnimation(false);
      setTimeout(() => {
        //回调
        let obj = {};
        obj.count = this.data.count;
        obj.sku = this.data.selectedSkuItem;
        if (this.data.goodsItem.groupId) {
          obj.groupId = this.data.goodsItem.groupId;
        }
        if (this.data.goodsItem.ptType) {
          obj.ptType = this.data.goodsItem.ptType;
        }
        if (this.data.goodsItem.isFqpt) {
          obj.isFqpt = true;
        }
        if (this.data.goodsItem.isBuyRightNow) {
          obj.isBuyRightNow = true;
        }
        this.triggerEvent('sure', obj, {});
      }, 400);
    }
  }
})